﻿using Furion.DatabaseAccessor;
using iWare.Wms.WorkerService.ThirdDB;
using Yitter.IdGenerator;

namespace iWare.Wms.WorkerService
{
    public class PurchaseERP : BackgroundService
    {
        private readonly ILogger<PurchaseERP> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public PurchaseERP(ILogger<PurchaseERP> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //定时同步采购单信息
                await Purchase();

                await Task.Delay(10 * 60 * 1000, stoppingToken);
            }
        }

        #region 定时同步采购单信息
        /// <summary>
        /// 定时同步采购单信息
        /// </summary>
        /// <returns></returns>
        public async Task Purchase()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取实体仓储
                var _purchaseOrderRep = Db.GetRepository<PurchaseOrder>(services);
                var whereTime = DateTime.Now.AddMonths(-1).ToString("yyyyMMdd");
                var purtcOutputList = await respository.SqlQueryAsync<PURTCOutput>
                     (@"select TC001, --采购单别
                               TC002, --采购单号
                               TC003, --采购日期
                               TC004, --供应商
                               TC009, --备注
                               TC011, --采购人员
                               TC023, --数量合计
                               TC047, --项目编号
                               UDF01, --收货地址
                               TC030, --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
                               TCD01  --是否结束 N:未结束、Y:结束 [DEF:""N""]
                        from PURTC where TCD01 = 'N' and TC030 = '3' and TC023 > 0 and TC003>'" + whereTime + "'  order by TC003 desc");

                //循环判断LES系统中是否包含该采购信息以及状态变化
                List<PurchaseOrder> PurchaseOrderList = new List<PurchaseOrder>();
                foreach (var item in purtcOutputList)
                {
                    var isExists = await _purchaseOrderRep
                        .AnyAsync(u => u.PurchaseNo == item.TC002 && u.PurchaseType == item.TC001 && u.Status != PurchaseStatusEnum.Delete);

                    //不存在执行新增操作
                    if (!isExists)
                    {
                        var addItem = new PurchaseOrder()
                        {
                            Id = YitIdHelper.NextId(),
                            PurchaseType = item.TC001?.Trim(),
                            PurchaseNo = item.TC002?.Trim(),
                            PurchaseDate = DateTime.ParseExact(item.TC003.ToString().Trim(), "yyyyMMdd",
                            System.Globalization.CultureInfo.CurrentCulture),
                            SupplierInfoCode = item.TC004?.Trim(),
                            Remark = item.TC009 == null ? "" : item.TC009.Trim(),
                            PurchaserUserId = item.TC011?.Trim(),
                            PurchaseNumber = item.TC023,
                            ProjectCode = item.TC047?.Trim(),
                            Address = item.UDF01?.Trim(),
                            Status = PurchaseStatusEnum.NotProgress,
                            CreatedUserName = "LES SYSTEM",
                            CreatedTime = DateTimeOffset.Now
                        };
                        PurchaseOrderList.Add(addItem);
                    }
                }

                //批量新增
                await _purchaseOrderRep.InsertNowAsync(PurchaseOrderList);

                Console.WriteLine("定时同步采购单信息");
            }
        }
        #endregion

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
